package fileTools

import (
	"app/pkg/config"
	"app/pkg/log"
	"fmt"
	"io"
	"math/rand"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"time"
)

func FilePutContent(text string, path string) (err error) {
	// err = MkDir(path)
	// if err != nil {
	// 	return
	// }
	file, err := os.Create(path)
	if err != nil {
		return
	}
	defer file.Close()
	_, err = file.WriteString(text)

	return
}

// 下载文件
func Download(uri string) (fsize int64, filename string, err error) {
	var buf = make([]byte, 1024)
	_, err = url.ParseRequestURI(uri)
	if err != nil {
		return
	}
	filename = RandomFileName(GetExt(uri))
	resp, err := http.Get(uri)
	if err != nil {
		return
	}
	defer resp.Body.Close()

	if resp.Body == nil {
		err = fmt.Errorf("body is nil")
		return
	}
	fsize, err = strconv.ParseInt(resp.Header.Get("Content-Length"), 10, 64)
	file, err := os.Create(filename)
	if err != nil {
		return
	}
	defer file.Close()
	for {
		nr, er := resp.Body.Read(buf)
		if nr > 0 {
			nw, ew := file.Write(buf[0:nr])
			// 写入出错
			if ew != nil {
				err = ew
				break
			}
			// 读取的数据长度不等于写入的数据长度
			if nr != nw {
				err = io.ErrShortWrite
				break
			}
		}
		if er != nil {
			if er != io.EOF {
				err = er
			}
			break
		}
	}
	return
}

// ext eg. .png
func RandomFileName(ext string) string {
	//pub dir
	_, f, _, _ := runtime.Caller(0)
	pub := filepath.Join(f, "../../../../pub/")
	now := time.Now()
	return fmt.Sprintf("%s/%s_%d%d%s", pub, now.Format("20060102"), (now.UnixNano() - now.Unix()), rand.Intn(100), ext)
}

// filename  https://sfxfsd/68/165202537707313535279.png
func GetExt(filename string) string {
	//去除?后面的字符串
	filename = strings.Split(filename, "?")[0]
	lastIndex := strings.LastIndex(filename, ".")
	if lastIndex > 0 {
		return filename[lastIndex+1:]
	}
	return "png"
}

func OssPath(tag string, ext string) string {
	now := time.Now()
	return fmt.Sprintf("%s/%s/%d%d.%s", tag, now.Format("20060102"), (now.UnixNano() - now.Unix()), rand.Intn(100), ext)
}

// 生成远端路径
func DstName(tag, ext string) string {
	now := time.Now()
	dir := fmt.Sprintf("%s/%s/%s", GetPubDir(), tag, now.Format("20060102"))
	fmt.Println(dir)
	fmt.Println(IsDir(dir))
	if !IsDir(dir) {
		err := MkDir(dir)
		if err != nil {
			log.NewError("mkdir err", dir)
			return ""
		}
	}
	return fmt.Sprintf("%s/%s/%d%d.%s", tag, now.Format("20060102"), (now.UnixNano() - now.Unix()), rand.Intn(100), ext)
}

// 生成远端路径
func DstAssignName(tag, ext, filename, secondDir string) string {
	fmt.Println("DstAssignName: ", tag, ext, filename, secondDir)
	now := time.Now()
	if secondDir == "" {
		secondDir = now.Format("20060102")
	}
	dir := fmt.Sprintf("%s/%s/%s", GetPubDir(), tag, secondDir)
	if !IsDir(dir) {
		err := MkDir(dir)
		if err != nil {
			log.NewError("mkdir err", dir)
			return ""
		}
	}
	return fmt.Sprintf("%s/%s/%s.%s", tag, secondDir, filename, ext)
}

// 根据远端路径返回本地路径
func GetLocalPathByDstName(dstName string) string {
	return fmt.Sprintf("%s/%s", GetPubDir(), dstName)
}

func GetPubDir() string {
	return config.Root + "/pub"
}

func IsDir(path string) bool {
	s, err := os.Stat(path)
	if err != nil {
		return false
	}
	return s.IsDir()
}

// Create a directory
func MkDir(path string) error {
	return os.MkdirAll(path, 0777)
}
